import { useParams } from 'react-router-dom';
import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import {
  ClearArticleAction,
  UpdateArticleByKeyWordAction,
} from '@/store/action/search';
import { useDispatch } from 'react-redux';
import { useEffect, useRef } from 'react';
import { useAppSelector } from '@/store';
import { InfiniteScroll } from 'antd-mobile';

export default function Result() {
  const params = useParams() as { keyword: string };
  const dispatch = useDispatch();
  const PageRef = useRef({ page: 0, per_page: 10 });
  const { ArtclesList } = useAppSelector((state) => state.search);
  useEffect(() => {
    /** 组件卸载清空Reducer数据 */
    return () => {
      dispatch(ClearArticleAction());
    };
    // eslint-disable-next-line
  }, [dispatch]);

  /** 异步函数 */
  async function loadMore() {
    PageRef.current.page += 1;
    let { page, per_page } = PageRef.current;
    await dispatch(
      UpdateArticleByKeyWordAction(params.keyword, page, per_page)
    );
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {ArtclesList?.map((item) => {
          return <ArticleItem ArticleData={item} key={item.art_id} />;
        })}
      </div>
      <InfiniteScroll
        loadMore={loadMore}
        hasMore={
          PageRef.current.per_page * PageRef.current.page <= ArtclesList.length
        }
      />
    </div>
  );
}
